// 存储单元工厂类
class CacheCell {
	constructor(data, timeout) {
		this.data = data
		this.timeout = timeout
		this.createTime = Date.now()
	}
}
/**
 *  缓存管理
 * */
class Cache {
	timeoutDefault = 60 * 60 * 2; // 单位s
	constructor(arg) {
		if (Cache.prototype.Instance === undefined) {
			Cache.prototype.Instance = this;
		}
		return Cache.prototype.Instance;
	}

	set(name, data, timeout = this.timeoutDefault) {
		uni.setStorageSync(name, new CacheCell(data, timeout));
	}

	get(name) {
		const {
			createTime,
			data,
			timeout
		} = uni.getStorageSync(name) || {};
		// 若没有存储过则默认返回空字符串
		if (!data) return '';
		const currentTime = Date.now()
		const overTime = (currentTime - createTime) / 1000

		if (overTime > timeout) {
			uni.removeStorageSync(name);
			return null
		}
		return data
	}
}

export default Cache
